<template>
  <el-card>
    <el-button type="primary" @click="openAddDialog">新增健康记录</el-button>
    <el-table :data="healthList" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="healthId" label="记录ID" width="80" />
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="sleepDuration" label="睡眠时长（小时）" />
      <el-table-column prop="sittingTime" label="久坐时间（小时）" />
      <el-table-column prop="periodStatus" label="经期状态" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteHealth(scope.row.healthId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form">
        <el-form-item label="用户ID">
          <el-input v-model="form.userId" />
        </el-form-item>
        <el-form-item label="睡眠时长">
          <el-input v-model="form.sleepDuration" />
        </el-form-item>
        <el-form-item label="久坐时间">
          <el-input v-model="form.sittingTime" />
        </el-form-item>
        <el-form-item label="经期状态">
          <el-input v-model="form.periodStatus" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getHealthRecordsByUserId, addHealthRecord, updateHealthRecord, deleteHealthRecord } from '@/api/health';
import { ElMessageBox } from 'element-plus';

const healthList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增健康记录');
const form = ref({ healthId: null, userId: '', sleepDuration: '', sittingTime: '', periodStatus: '' });
let isEdit = false;

const loadHealth = async () => {
  healthList.value = await getHealthRecordsByUserId(1);
};

const openAddDialog = () => {
  isEdit = false;
  dialogTitle.value = '新增健康记录';
  form.value = { healthId: null, userId: '', sleepDuration: '', sittingTime: '', periodStatus: '' };
  dialogVisible.value = true;
};

const openEditDialog = (record) => {
  isEdit = true;
  dialogTitle.value = '编辑健康记录';
  form.value = { ...record };
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (isEdit) {
    await updateHealthRecord(form.value);
  } else {
    await addHealthRecord(form.value);
  }
  dialogVisible.value = false;
  loadHealth();
};

const deleteHealth = async (healthId) => {
  await ElMessageBox.confirm('确定删除该记录吗?', '提示', { type: 'warning' });
  await deleteHealthRecord(healthId);
  loadHealth();
};

onMounted(() => {
  loadHealth();
});
</script>
